package com.hboxs.asl.filter;

import com.hboxs.asl.Principal;
import com.hboxs.asl.entity.Member;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * Filter -- 微信登陆
 */
@Component(value = "wechatLoginFilter")
public class WechatLoginFilter extends OncePerRequestFilter {
    protected Logger logger = Logger.getLogger(getClass());

    /**
     * 首页-商城首页
     */
    private static final String INDEX = "/weChat/";

    /**
     * "重定向URL"参数名称
     */
    private static final String REDIRECT_URL_PARAMETER_NAME = "callback";

    /**
     * 微信登录URL
     */
    private static final String WECHAT_LOGIN_URL = "/wechat/login.htm";

    /**
     * 账号密码登录，非微信登录
     */
    private static final String MEMBER_LOGIN_URL = "/wechat/member/login.htm";
    private static final String MEMBER_REGISTER_URL = "/wechat/member/register.htm";

    private static final String[] IGNORE_URLS = new String[]{"/404.html", "/weChat/member/autoLogin.htm",MEMBER_LOGIN_URL,MEMBER_REGISTER_URL

    ,"/weChat/index.htm"
    ,"/weChat/productCategory/list.htm"
    ,"/weChat/cart/list.htm"
    ,"/weChat/profile/index.htm"
    ,"/weChat/product/list.htm"
    ,"/weChat/product/detail.htm"
    ,"/weChat/ad-list.htm"

    };

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        HttpSession session = request.getSession();
        Principal principal = (Principal) session.getAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME);

        if (principal == null && !isIgnoreUrl(request.getRequestURI())) {
            String requestType = request.getHeader("X-Requested-With");
            if (requestType == null || !requestType.equalsIgnoreCase("XMLHttpRequest")) {
                String location;
                if (request.getMethod().equalsIgnoreCase("GET")) {
                    String redirectUrl = request.getQueryString() != null ? request.getRequestURI() + "?" + request.getQueryString() : request.getRequestURI();
//                    location = request.getContextPath() + WECHAT_LOGIN_URL + "?scope=snsapi_userinfo&" + REDIRECT_URL_PARAMETER_NAME + "=" + URLEncoder.encode(redirectUrl, "UTF-8");
                    location = request.getContextPath() + MEMBER_LOGIN_URL + "?scope=snsapi_userinfo&" + REDIRECT_URL_PARAMETER_NAME + "=" + URLEncoder.encode(redirectUrl, "UTF-8");
                } else {
//                    location = request.getContextPath() + WECHAT_LOGIN_URL + "?scope=snsapi_userinfo&" + REDIRECT_URL_PARAMETER_NAME + "=" + URLEncoder.encode(request.getContextPath() + INDEX, "UTF-8");
                    location = request.getContextPath() + MEMBER_LOGIN_URL + "?scope=snsapi_userinfo&" + REDIRECT_URL_PARAMETER_NAME + "=" + URLEncoder.encode(request.getContextPath() + INDEX, "UTF-8");
                }
                response.sendRedirect(location);
                return;
            }
        }
        filterChain.doFilter(request, response);
        return;
    }

    private boolean isIgnoreUrl(String url) {
        for (String uri : IGNORE_URLS) {
            if (url.contains(uri)) {
                return true;
            }
        }
        return false;
    }
}
